/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> ol转孔 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step: "unit.+",
		step2:"unit",
		auto_save: "No",
		units: "mm",
		rout: "ol"
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }

	var steplists = GEN.getStepList({job:job});
	if(steplists.length == 0){return "该料号没有step"}
	steplists = steplists.filter(function(name){
		var reg = new RegExp(par.step, "ig")
		return reg.test(name)
	})
	if (steplists.length == 0 && par.step2) {
		steplists = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	steplists.forEach(function(step){
		GEN.openStep({job:job, name:step})
		GEN.units({type:par.units})
		GEN.affectedLayer({affected:'no',mode:'all'})
		GEN.selClearFeature()
		GEN.workLayer({name:par.rout,display_number:2,clear_before:'yes'})
		GEN.COM("sel_design2rout,det_tol=50,con_tol=50,rad_tol=25")
		var feats = GEN.getFeatures({job:job,step:step,layer:par.rout,options:"feat_index",units:"mm"})
		feats = feats.filter(function(item){
			return item.type === "arc" && item.xs === item.xe && item.ys === item.ye
		})
		feats = feats.filter(function(item){
			var d = 2*Math.sqrt((item.xe - item.xc)*(item.xe - item.xc) + (item.ye - item.yc)*(item.ye - item.yc))*1000
			return  d <= 6000
		})
		feats.forEach(function(item) {
			GEN.selLayerFeat({layer:par.rout, index:item.index,operation:"select"})
		})
		//  npth  move至drl
		if(GEN.getSelectCount() >0 ) {
			GEN.selMoveOther({target_layer:'ol_tmp',invert:'no',dx:0,dy:0,size:0})
			GEN.workLayer({name:"ol_tmp",display_number:2,clear_before:'yes'})
			GEN.units({type:"mm"})
			GEN.COM("sel_cut_data,det_tol=25.4,con_tol=25.4,rad_tol=2.54,filter_overlaps=no,delete_doubles=no,use_order=yes,ignore_width=yes,ignore_holes=none,start_positive=yes,polarity_of_touching=same")
			GEN.units({type:"inch"})
			GEN.COM("sel_cont2pad,match_tol=1,restriction=,min_size=0.01,max_size=100000,suffix=+++")
			GEN.units({ type: par.units });
			GEN.COM("cur_atr_set,attribute=.drill,option=non_plated")
			GEN.COM("sel_change_atr,mode=add")
			GEN.selMoveOther({target_layer:'drl',invert:'no',dx:0,dy:0,size:0})
			GEN.deleteLayer({job:job,layer:"ol_tmp"})
		}

		if(GEN.isLayerExists({job:job,layer:"pt-ol"})) {
			GEN.workLayer({name:"pt-ol",display_number:2,clear_before:'yes'})
			GEN.COM("sel_design2rout,det_tol=50,con_tol=50,rad_tol=25")
			var feats2 = GEN.getFeatures({job:job,step:step,layer:"pt-ol",options:"feat_index",units:"mm"})
			feats2 = feats2.filter(function(item){
				return item.type === "arc" && item.xs === item.xe && item.ys === item.ye
			})
			feats2 = feats2.filter(function(item){
				var d = 2*Math.sqrt((item.xe - item.xc)*(item.xe - item.xc) + (item.ye - item.yc)*(item.ye - item.yc))*1000
				return  d <= 12000
			})
			feats2.forEach(function(item) {
				GEN.selLayerFeat({layer:"pt-ol", index:item.index,operation:"select"})
			})
			//  npth  move至drl
			if(GEN.getSelectCount() >0 ) {
				GEN.selMoveOther({target_layer:'ol_tmp',invert:'no',dx:0,dy:0,size:0})
				GEN.workLayer({name:"ol_tmp",display_number:2,clear_before:'yes'})
				GEN.units({type:"mm"})
				GEN.COM("sel_cut_data,det_tol=25.4,con_tol=25.4,rad_tol=2.54,filter_overlaps=no,delete_doubles=no,use_order=yes,ignore_width=yes,ignore_holes=none,start_positive=yes,polarity_of_touching=same")
				GEN.units({type:"inch"})
				GEN.COM("sel_cont2pad,match_tol=1,restriction=,min_size=0.01,max_size=100000,suffix=+++")
				GEN.units({ type: par.units });
				GEN.COM("cur_atr_set,attribute=.drill,option=plated")
				GEN.COM("sel_change_atr,mode=add")
				GEN.selMoveOther({target_layer:'drl',invert:'no',dx:0,dy:0,size:0})
				GEN.deleteLayer({job:job,layer:"ol_tmp"})
			}
		}
		
	})

	

	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) {
			Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {status: Status,result_data: resultData};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}